/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2023-12-28 19:07:29
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-01-29 08:59:37
 * @FilePath: /yt-devops/lib/pages/devices/device_tab/device_detail/electric_meter/electric_meter_view.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:yt_devops/components/app_bar/app_bar_widget.dart';
import 'package:yt_devops/components/card_wrap.dart';
import 'package:yt_devops/model/device_model.dart';
import 'package:yt_devops/model/device_obj/group_config_model.dart';
import 'package:yt_devops/model/device_obj/properties_model.dart';
import 'package:yt_devops/pages/devices/device_tab/utils/device_util.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'electric_meter_controller.dart';

class ElectricMeterPage extends GetView<ElectricMeterController> {
  /// 设备详情
  DeviceModel? deviceModel;

  /// 设备id;
  int deviceId;

  ElectricMeterPage(
      {Key? key, required this.deviceId, required this.deviceModel})
      : super(key: key);

  double sreenWidth = 343.w - 32.w;

  GlobalKey appBarKey = GlobalKey();

  @override
  ElectricMeterController get controller => Get.put(ElectricMeterController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ElectricMeterController>(
      initState: (state) {
        if (deviceModel != null) {
          controller.deviceId = deviceId;
          deviceModel = deviceModel;
          controller.init(deviceModel!);
        }
      },
      dispose: (state) => Get.delete<ElectricMeterController>(),
      builder: (controller) => Scaffold(
          appBar: AppBarWidget.withMorePopMenu(
            deviceModel?.name ?? '',
            context,
            appBarKey,
            data: controller.actionList,
            onItemClick: (index, value) => controller.toService(value),
          ),
          body: ListView.builder(
            itemBuilder: (context, index) => CardWrap(
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    if (!FuncUtils.isEmpty(controller.models[index].name))
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          DeviceUtil.headTitle(controller.models[index].name!),
                          if (index == 0) connectStatusWidget()
                        ],
                      ),
                    ...getGridRows(controller.models[index].children,
                        controller.dataSource)
                  ]),
            ),
            itemCount: controller.models.length,
          )),
    );
  }

  connectStatusWidget() {
    return Text(
      controller.connectStatus?.label ?? '',
      style: TextStyle(
          fontSize: 14.sp,
          color: controller.connectStatus == ConnectStatusType.on
              ? Colour.green
              : Colour.lightTextColor,
          height: 2.5),
    );
  }

  List<Widget> getGridRows(
      List<GroupConfigModel> items, Map<String, dynamic>? dataSource) {
    List<Widget> rows = [], cols = [];
    int itemCount = items.length, index = 0;
    Widget container;
    while (index < itemCount) {
      List<Widget> cols = [];
      if (index + 1 < itemCount) {
        cols.addAll([
          getGridCell(items[index], dataSource, 0.54 * sreenWidth),
          getGridCell(items[index + 1], dataSource, 0.46 * sreenWidth)
        ]);
        index = index + 2;
      } else {
        cols.add(
          getGridCell(items[index], dataSource, 0.54 * sreenWidth),
        );
        index = index + 1;
      }
      container = Container(
        padding: EdgeInsets.only(bottom: 20.h),
        margin: EdgeInsets.only(top: 18.h),
        decoration: const BoxDecoration(
            border: Border(bottom: BorderSide(color: Colour.dividerColor))),
        child:
            Row(crossAxisAlignment: CrossAxisAlignment.start, children: cols),
      );
      rows.add(container);
    }
    return rows;
  }

  getGridCell(
      GroupConfigModel model, Map<String, dynamic>? dataSource, double width) {
    return SizedBox(
      width: width,
      child: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
        Padding(
          padding: EdgeInsets.only(bottom: 8.h),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Image.asset(
                model.logo ?? '',
                errorBuilder: (context, error, stackTrace) =>
                    Image.asset(ImageAssets.networkImageLoadingFailure),
              ),
              Expanded(
                child: Padding(
                  padding: EdgeInsets.only(left: 12.w),
                  child: Text(
                    model.name!,
                    style: TextStyles.f14,
                    maxLines: 2,
                  ),
                ),
              )
            ],
          ),
        ),
        ...model.children?.map((e) => Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    SizedBox(
                      width: 100.w,
                      child: Text(
                        '${e.name}：',
                        style: TextStyles.lf14.copyWith(height: 1.8),
                      ),
                    ),
                    Text(
                      FuncUtils.formatModelValue(dataSource?[e.id],
                              (e as PropertiesModel).dataType,
                              isShowUnit: false)
                          .toString(),
                      style: controller.connectStatus == ConnectStatusType.on
                          ? TextStyles.f14
                          : TextStyle(
                              fontSize: 14.sp, color: Colour.offlineTextColor),
                    )
                  ],
                )) ??
            []
      ]),
    );
  }
}
